import os
from datetime import datetime, timezone, timedelta

import random
import urllib, urllib3, sys, uuid
from django.contrib import messages
# 上面这个用来显示提示信息
from django.core.files.storage import FileSystemStorage
from django.core.paginator import Paginator
from django.db.models.functions import datetime
from django.shortcuts import render, get_object_or_404

# Create your views here.
from djangoProject.settings import MEDIA_ROOT
from . import models  # 这里的from polls不是必要的，因为polls是当前目录，所以可以省略
from users.models import Student, Admin, Book
from django.http import HttpResponse
from django.conf import settings

# 导出未Excel
from openpyxl import Workbook

def start(request):
    return render(request, "start.html")


def welcome(request):
    if stu:
        return render(request, "welcome.html", {'stucc': stucc})
    elif adm:
        return render(request, "welcome.html", {'admdd': admdd})
    return render(request, "welcome.html")

def login(request):
    global stu
    global adm
    if request.method == "POST":
        identity = request.POST.get('identity')
        if identity == '学生':
            stu_id = request.POST.get('id')
            stu_pwd = request.POST.get('pwd')
            if not stu_id.isdigit():
                return render(request, 'login.html', {'err': '学号必须为数字'})
            if Student.objects.filter(stu_id=stu_id).exists():
                stu = Student.objects.filter(stu_id=stu_id)[0]
                if stu_pwd == stu.stu_pwd:
                    global stucc
                    stucc = models.Student.objects.get(stu_id=stu_id)
                    return render(request, 'welcome.html', {'stucc': stucc})
                else:
                    return render(request, 'login.html', {'err': '密码不正确'})
            else:
                return render(request, 'login.html', {'err': '用户不存在'})
        elif identity == '管理员':
            adm_id = request.POST.get('id')
            adm_pwd = request.POST.get('pwd')
            if not adm_id.isdigit():
                return render(request, 'login.html', {'err': '账号必须为数字'})
            if Admin.objects.filter(adm_id=adm_id).exists():
                adm = Admin.objects.filter(adm_id=adm_id)[0]
                if adm_pwd == adm.adm_pwd:
                    global admdd
                    admdd = models.Admin.objects.get(adm_id=adm_id)
                    return render(request, 'welcome.html', {'admdd': admdd})
                    # admdd = {'adm_id': adm.adm_id, 'adm_pwd': adm.adm_pwd, 'adm_phone': adm.adm_phone}
                else:
                    return render(request, 'login.html', {'err': '密码不正确'})
            else:
                return render(request, 'login.html', {'err': '用户不存在'})
    return render(request, 'login.html')


def register(request):
    if request.method == "POST":
        id = request.POST.get('id')
        pwd = request.POST.get('pwd')
        pwd2 = request.POST.get('pwd2')
        if Student.objects.filter(stu_id=id).exists():
            return render(request, 'register.html', {'err': '该学号已注册过'})
        if pwd != pwd2:
            return render(request, 'register.html', {'err': '两次输入的密码不一致'})
        global stu
        stu = Student()
        stu.stu_id = id
        stu.stu_pwd = pwd
        stu.save()
        global stucc
        stucc = models.Student.objects.get(stu_id=id)
        return render(request, "regSuccess.html", {'stucc': stucc})
    return render(request, 'register.html')


def phoneLogin(request):
    global stu
    global adm
    if request.method == "POST":
        action = request.POST.get('action')
        phone = request.POST.get('phone')
        identity = request.POST.get('identity')
        if len(phone) != 11:
            return render(request, 'phoneLogin.html', {'err': '手机号格式不正确'})
        if action == '发送验证码':
            if identity == '学生' and Student.objects.filter(stu_phone=phone).exists():
                stu = models.Student.objects.filter(stu_phone=phone)[0]
                stu.stu_phoneCode = createPhoneCode(phone)
                stu.stu_codeAcquireTime = datetime.datetime.now().replace(tzinfo=timezone.utc)
                stu.save()
                code = '验证码已发送，将在5分钟后失效'
            elif identity == '管理员' and Admin.objects.filter(adm_phone=phone).exists():
                adm = models.Admin.objects.filter(adm_phone=phone)[0]
                adm.adm_phoneCode = createPhoneCode(phone)
                adm.adm_codeAcquireTime = datetime.datetime.now().replace(tzinfo=timezone.utc)
                adm.save()
                code = '验证码已发送，将在5分钟后失效'
            else:
                code = '该手机号未注册或该手机号并不属于该用户身份'
            return render(request, 'phoneLogin.html', {'code': code})
        elif action == '登录':
            phoneCode = request.POST.get('code')
            if len(phoneCode) != 6:
                return render(request, "phoneLogin.html", {'err': '验证码格式不正确'})
            if identity == '学生' and Student.objects.filter(stu_phone=phone).exists():
                stu = models.Student.objects.filter(stu_phone=phone)[0]
                if stu.stu_phoneCode == '':
                    return render(request, "phoneLogin.html", {'err': '请先发送验证码'})
                if stu.stu_phoneCode == phoneCode:  # 验证码正确
                    # 验证码是否过期
                    nowtime = datetime.datetime.now().replace(tzinfo=timezone.utc)
                    if (nowtime - stu.stu_codeAcquireTime).seconds > 60 * 5:
                        return render(request, "phoneLogin.html", {'err': '验证码已过期'})
                    stu.stu_phoneCode = ''
                    stu.save()
                    global stucc
                    stucc = models.Student.objects.get(stu_phone=phone)
                    return render(request, "stu/stu_index.html", {'stucc': stucc})
                else:
                    return render(request, "phoneLogin.html", {'err': '验证码错误'})
            elif identity == '管理员' and Admin.objects.filter(adm_phone=phone).exists():
                adm = models.Admin.objects.filter(adm_phone=phone)[0]
                if adm.adm_phoneCode == '':
                    return render(request, "phoneLogin.html", {'err': '请先发送验证码'})
                if adm.adm_phoneCode == phoneCode:  # 验证码正确
                    # 验证码是否过期
                    nowtime = datetime.datetime.now().replace(tzinfo=timezone.utc)
                    if (nowtime - adm.adm_codeAcquireTime).seconds > 60 * 5:
                        return render(request, "phoneLogin.html", {'err': '验证码已过期'})
                    adm.adm_phoneCode = ''
                    adm.save()
                    global admdd
                    admdd = models.Admin.objects.get(adm_phone=phone)
                    return render(request, "adm/adm_index.html", {'admdd': admdd})
                else:
                    return render(request, "phoneLogin.html", {'err': '验证码错误'})
            else:
                return render(request, "phoneLogin.html", {'err': '该手机号未注册或该手机号并不属于该用户身份'})
    return render(request, 'phoneLogin.html')


def regSuccess(request):
    return render(request, 'regSuccess.html', {'stucc': stucc})


def stu_index(request):
    notice = models.Notice.objects.all()
    paginator = Paginator(notice, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    if request.method == "GET":
        paginator = Paginator(notice, 5)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
    return render(request, "stu/stu_index.html", {'stucc': stucc, 'notice': page_obj})


def stu_info(request):
    # return render(request, "stu_info.html", {'stuaa': stuaa, 'stuaaUrl': stuaaUrl})
    return render(request, "stu/stu_info.html", {'stucc': stucc})


def stu_infoAlter(request):
    global stucc
    stucc = models.Student.objects.get(stu_id=stu.stu_id)
    if request.method == "POST":
        action = request.POST.get('action')
        phone = request.POST.get('phone')
        user = models.Student.objects.get(stu_id=stucc.stu_id)
        if len(phone) != 11:
            return render(request, "stu/stu_infoAlter.html", {'stucc': stucc, 'err': '手机号格式不正确'})
        if action == '获取验证码':
            user.stu_phoneCode = createPhoneCode(phone)
            user.stu_codeAcquireTime = datetime.datetime.now().replace(tzinfo=timezone.utc)
            user.save()
            return render(request, "stu/stu_infoAlter.html", {'stucc': stucc, 'err': '验证码已发送，将在5分钟后失效'})
        if action == '提交':
            stu_phoneCode = request.POST.get('code')
            if len(stu_phoneCode) != 6:
                return render(request, "stu/stu_infoAlter.html", {'stucc': stucc, 'err': '验证码格式不正确'})
            # 验证码是否过期
            nowtime = datetime.datetime.now().replace(tzinfo=timezone.utc)
            if (nowtime - user.stu_codeAcquireTime).seconds > 60 * 5:
                return render(request, "stu/stu_infoAlter.html", {'stucc': stucc, 'err': '验证码已过期'})
            # 验证码是否正确
            if stu_phoneCode != user.stu_phoneCode:
                return render(request, "stu/stu_infoAlter.html", {'stucc': stucc, 'err': '验证码不正确'})
            # 验证码正确，修改手机号
            Student.objects.filter(stu_id=stucc.stu_id).update(stu_phone=phone)
            user.stu_phoneCode = ''
            Student.objects.filter(stu_id=stucc.stu_id).update(stu_codeAcquireTime=user.stu_codeAcquireTime,
                                                               stu_phoneCode=user.stu_phoneCode)
            # ---------------------------------------------
            name = request.POST.get('name')
            gender = request.POST.get('gender')
            age = request.POST.get('age')
            college = request.POST.get('college')
            major = request.POST.get('major')
            stu.stu_name = name
            stu.stu_gender = gender
            stu.stu_phone = phone
            stu.stu_age = age
            stu.stu_college = college
            stu.stu_major = major
            stu.save()
            # 获取一个文件管理器对象
            file = request.FILES['pic']
            file_name = f"{stu.stu_id}.jpg"
            new_name = f"/media/stuUsers/{stu.stu_id}.jpg"
            # 将要保存的地址和文件名称
            where = os.path.join(settings.MEDIA_ROOT, 'stuUsers', file_name)
            if stu.avatar:
                # old_image_path = os.path.join(settings.MEDIA_ROOT, "stuUsers", file_name)
                # print("old_image_path: "+old_image_path)
                # 这个old_path是对的 old_image_path: D:\pyTest\djangoProject\statics\media\stuUsers\514.jpg
                if os.path.exists(where):
                    os.remove(where)
            # 分块保存image
            with open(where, 'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)
            # 上传文件名称到数据库
            stu.stu_borrowNum = models.Borrow.objects.filter(stuId_id=stu.stu_id, isReturn=False).count()
            Student.objects.filter(stu_id=stu.stu_id).update(avatar=new_name, stu_borrowNum=stu.stu_borrowNum)
            stucc = models.Student.objects.get(stu_id=stu.stu_id)
            return render(request, "stu/stu_index.html", {'stucc': stucc})
    return render(request, "stu/stu_infoAlter.html", {'stucc': stucc})  # {'stu_id': stu.stu_id}


def stu_pwdAlter(request):
    if request.method == "POST":
        stu_pwd = request.POST.get('pwd')
        stu_pwd2 = request.POST.get('pwd2')
        if stu_pwd != stu_pwd2:
            return render(request, "stu/stu_pwdAlter.html", {'err': '两次输入的密码不相同', 'stu_id': stu.stu_id})
        if stu_pwd == stu.stu_pwd:
            return render(request, "stu/stu_pwdAlter.html", {'err': '新密码不能与旧密码相同', 'stu_id': stu.stu_id})
        stu.stu_pwd = stu_pwd
        stu.save()
        return render(request, "stu/stu_index.html", {'stucc': stucc})
    return render(request, "stu/stu_pwdAlter.html", {'stucc': stucc})


def stu_book(request):
    book_queryset = models.Book.objects.all()
    paginator = Paginator(book_queryset, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    quest = request.GET.get('quest')
    category = request.GET.get('category')
    if request.method == "GET":
        if category == 'book_name':
            book_queryset = models.Book.objects.filter(book_name__contains=quest)
        elif category == 'book_author':
            book_queryset = models.Book.objects.filter(book_author__contains=quest)
        elif category == 'book_publisher':
            book_queryset = models.Book.objects.filter(book_publisher__contains=quest)
        elif category == 'book_id':
            book_queryset = models.Book.objects.filter(book_id__contains=quest)
    if request.method == "POST":
        category = request.POST.get('category')  # 获取下拉框的值
        form_id = request.POST.get('form_id')
        # if form_id == 'check':      # 借书
        #     book_id = request.POST.get('book_id')
        #     book = models.Book.objects.get(book_id=book_id)
        #     return render(request, "stu/stu_bookInfo.html", {'stucc': stucc, 'book': book})
        if form_id == 'search':  # 查询图书
            quest = request.POST.get('quest')
            if category == 'book_name':
                book_queryset = models.Book.objects.filter(book_name__contains=quest)
            elif category == 'book_author':
                book_queryset = models.Book.objects.filter(book_author__contains=quest)
            elif category == 'book_publisher':
                book_queryset = models.Book.objects.filter(book_publisher__contains=quest)
            elif category == 'book_id':
                book_queryset = models.Book.objects.filter(book_id__contains=quest)
            if book_queryset:
                err = ''
            else:
                err = '不存在该图书'
        else:
            err = ''
    else:
        err = ''
    paginator = Paginator(book_queryset, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, "stu/stu_book.html", {'stucc': stucc, 'book_queryset': page_obj, 'quest': quest,
                                                 'category': category, 'err': err})


def stu_bookInfo(request):
    book_id = request.POST.get('book_id')
    book = models.Book.objects.get(book_id=book_id)
    if request.method == "POST":
        form_id = request.POST.get('form_id')
        # -----------------------------------------
        # 下面这个原先是stu_book的查看书籍记录，因为form表单的关系，而且action放的是/stu_bookInfo，这样就可以把url进行改变
        # （原先通过form表单提交的时候，如果action不写东西，那么跳转后url还是不会改变
        if form_id == 'check':  # 借书
            book_id = request.POST.get('book_id')
            book = models.Book.objects.get(book_id=book_id)
            return render(request, "stu/stu_bookInfo.html", {'stucc': stucc, 'book': book})
        # -----------------------------------------
        stu_id = request.POST.get('stu_id')
        student = models.Student.objects.get(stu_id=stu_id)
        if book.book_num == 0:
            return render(request, "stu/stu_bookInfo.html", {'stucc': stucc, 'book': book, 'err': '该书已借完'})
        if student.stu_borrowNum >= 5:
            return render(request, "stu/stu_bookInfo.html", {'stucc': stucc, 'book': book, 'err': '你的借书数量已达5本上限'})
        day = request.POST.get('day')
        if day == '1天':
            due_date = datetime.datetime.now() + timedelta(days=1)
        elif day == '3天':
            due_date = datetime.datetime.now() + timedelta(days=3)
        elif day == '7天':
            due_date = datetime.datetime.now() + timedelta(days=7)
        # 添加借阅记录
        models.Borrow.objects.create(bookId_id=book_id, stuId_id=stu_id, borrow_date=datetime.datetime.now(),
                                     due_date=due_date,
                                     isReturn=False)
        student.stu_borrowNum += 1
        student.save()
        # 更新图书数量
        book.book_num -= 1
        book.save()
        notice = models.Notice.objects.all()
        paginator = Paginator(notice, 5)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        # 返回借阅成功页面
        return render(request, "stu/stu_index.html", {'stucc': stucc, 'notice': page_obj})
    return render(request, "stu/stu_bookInfo.html", {'stucc': stucc, 'book': book})


def stu_borrow(request):
    bw = models.Borrow.objects.filter(stuId=stucc.stu_id)
    paginator = Paginator(bw, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    quest = request.GET.get('quest')
    category = request.GET.get('category')
    if request.method == "GET":
        if category == 'book_id':
            bw = models.Borrow.objects.filter(bookId_id=quest)
    if request.method == "POST":
        category = request.POST.get('category')  # 获取下拉框的值
        form_id = request.POST.get('form_id')
        page = request.POST.get('page')
        if form_id == 'search':  # 查询借阅记录
            quest = request.POST.get('quest')
            if category == 'book_id':
                bw = models.Borrow.objects.filter(bookId_id=quest)
            if bw:
                err = ''
            else:
                err = '不存在该借阅记录'
        else:
            err = ''
    else:
        err = ''
    paginator = Paginator(bw, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, "stu/stu_borrow.html", {'stucc': stucc, 'bw': page_obj, 'quest': quest,
                                                   'category': category, 'err': err})


def stu_myBook(request):
    if request.method == "POST":
        borrow_id = request.POST.get('borrow_id')
        book_id = request.POST.get('book_id')
        book = models.Book.objects.get(book_id=book_id)
        book.book_num += 1
        book.save()
        returnBook = models.Borrow.objects.get(borrow_id=borrow_id, isReturn=False)
        returnBook.isReturn = True
        returnBook.return_date = datetime.datetime.now()
        returnBook.save()
        student = models.Student.objects.get(stu_id=stucc.stu_id)
        student.stu_borrowNum -= 1
        student.save()
    book_queryset = models.Borrow.objects.filter(stuId=stucc.stu_id, isReturn=False)
    return render(request, "stu/stu_myBook.html", {'stucc': stucc, 'book_queryset': book_queryset})


def adm_index(request):
    notice = models.Notice.objects.all()
    paginator = Paginator(notice, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    if request.method == 'POST':
        form_id = request.POST.get('form_id')
        user_id = request.POST.get('user_id')
        notice_id = request.POST.get('notice_id')
        if form_id == 'delete':
            models.Notice.objects.filter(notice_id=notice_id).delete()
            notice = models.Notice.objects.all()
            paginator = Paginator(notice, 5)
            page_number = request.GET.get('page')
            page_obj = paginator.get_page(page_number)
            return render(request, 'adm/adm_index.html', {'admdd': admdd, 'notice': page_obj})
    return render(request, "adm/adm_index.html", {'admdd': admdd, 'notice': page_obj})


def noticeContent(request):
    if request.method == 'POST':
        form_id = request.POST.get('form_id')
        user_id = request.POST.get('user_id')
        notice_id = request.POST.get('notice_id')
        if form_id == 'check':
            if models.Student.objects.filter(stu_id=user_id).exists(): #判断是学生进入的这个页面
                flag = 'stu'
            elif models.Admin.objects.filter(adm_id=user_id).exists(): #判断是管理员进入的这个页面
                flag = 'adm'
            notice = models.Notice.objects.get(notice_id=notice_id)
            return render(request, 'noticeContent.html', {'notice': notice, 'flag': flag})
    return render(request, 'noticeContent.html')


def noticeAddAlter(request):
    if request.method == 'POST':
        form_id = request.POST.get('form_id')
        notice_id = request.POST.get('notice_id')
        if form_id == 'AddAlter':
            if models.Notice.objects.filter(notice_id=notice_id).exists(): #判断是修改
                admId_id = request.POST.get('admId_id')
                notice_content = request.POST.get('notice_content')
                notice_title = request.POST.get('notice_title')
                notice_date = request.POST.get('notice_date')
                models.Notice.objects.filter(notice_id=notice_id).update(notice_id=notice_id, admId_id=admId_id,
                                                                         notice_content=notice_content, notice_title=notice_title, notice_date=notice_date)
            else:# 判断是增加图书
                notice_id = request.POST.get('notice_id')
                admId_id = request.POST.get('admId_id')
                notice_content = request.POST.get('notice_content')
                notice_title = request.POST.get('notice_title')
                notice_date = request.POST.get('notice_date')
                nt = models.Notice(notice_id=notice_id, admId_id=admId_id, notice_content=notice_content,
                                   notice_title=notice_title, notice_date=notice_date)
                nt.save()
            notice = models.Notice.objects.all()
            paginator = Paginator(notice, 5)
            page_number = request.GET.get('page')
            page_obj = paginator.get_page(page_number)
            return render(request, 'adm/adm_index.html', {'admdd': admdd, 'notice': page_obj})
        elif form_id == 'alter':
            notice = models.Notice.objects.get(notice_id=notice_id)
            return render(request, 'noticeAddAlter.html', {'notice': notice, 'admdd': admdd})
    return render(request, 'noticeAddAlter.html',  {'admdd': admdd})


def adm_info(request):
    # admdd = {'adm_id': adm.adm_id, 'adm_pwd': adm.adm_pwd, 'adm_phone': adm.adm_phone}
    return render(request, "adm/adm_info.html", {'admdd': admdd})


def adm_infoAlter(request):
    global admdd
    if request.method == "POST":
        action = request.POST.get('action')
        adm_phone = request.POST.get('phone')
        user = models.Admin.objects.get(adm_id=admdd.adm_id)
        if len(adm_phone) != 11:
            return render(request, "adm/adm_infoAlter.html", {'admdd': admdd, 'err': '手机号格式不正确'})
        if action == '获取验证码':
            user.adm_phoneCode = createPhoneCode(adm_phone)
            user.adm_codeAcquireTime = datetime.datetime.now().replace(tzinfo=timezone.utc)
            user.save()
            return render(request, "adm/adm_infoAlter.html", {'admdd': admdd, 'err': '验证码已发送，将在5分钟后失效'})
        if action == '提交':
            adm_phoneCode = request.POST.get('code')
            if len(adm_phoneCode) != 6:
                return render(request, "adm/adm_infoAlter.html", {'admdd': admdd, 'err': '验证码格式不正确'})
            # 验证码是否过期
            nowtime = datetime.datetime.now().replace(tzinfo=timezone.utc)
            if (nowtime - user.adm_codeAcquireTime).seconds > 60 * 5:
                return render(request, "adm/adm_infoAlter.html", {'admdd': admdd, 'err': '验证码已过期'})
            # 验证码是否正确
            if adm_phoneCode != user.adm_phoneCode:
                return render(request, "adm/adm_infoAlter.html", {'admdd': admdd, 'err': '验证码不正确'})
            # 验证码正确，修改手机号
            user.adm_phoneCode = ''
            name = request.POST.get('name')
            user.adm_name = name
            user.save()
            Admin.objects.filter(adm_id=admdd.adm_id).update(adm_phone=adm_phone)
            admdd = models.Admin.objects.get(adm_id=adm.adm_id)
            return render(request, "adm/adm_info.html", {'admdd': admdd})
    return render(request, "adm/adm_infoAlter.html", {'admdd': admdd})


def adm_pwdAlter(request):
    if request.method == "POST":
        adm_pwd = request.POST.get('pwd')
        adm_pwd2 = request.POST.get('pwd2')
        if adm_pwd != adm_pwd2:
            return render(request, "adm/adm_pwdAlter.html", {'admdd': admdd, 'err': '两次密码不一致'})
        if adm_pwd == adm.adm_pwd:
            return render(request, "adm/adm_pwdAlter.html", {'admdd': admdd, 'err': '密码不能与原密码相同'})
        adm.adm_pwd = adm_pwd
        adm.save()
        # global admdd
        # admdd = models.Admin.objects.get(adm_id=adm.adm_id)
        notice = models.Notice.objects.all()
        paginator = Paginator(notice, 5)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        return render(request, "adm/adm_index.html", {'admdd': admdd, 'notice': page_obj})
    return render(request, "adm/adm_pwdAlter.html", {'admdd': admdd})


def adm_stuInfo(request):
    stu_queryset = models.Student.objects.all()
    paginator = Paginator(stu_queryset, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    quest = request.GET.get('quest')
    category = request.GET.get('category')
    if request.method == "GET":
        if category == 'stu_id':
            stu_queryset = models.Student.objects.filter(stu_id__contains=quest)
        elif category == 'stu_name':
            stu_queryset = models.Student.objects.filter(stu_name__contains=quest)
        elif category == 'stu_college':
            stu_queryset = models.Student.objects.filter(stu_college__contains=quest)
        elif category == 'stu_major':
            stu_queryset = models.Student.objects.filter(stu_major__contains=quest)
        elif category == 'stu_phone':
            stu_queryset = models.Student.objects.filter(stu_phone__contains=quest)
    if request.method == "POST":
        category = request.POST.get('category')  # 获取下拉框的值
        form_id = request.POST.get('form_id')
        if form_id == 'search':  # 查询学生信息
            quest = request.POST.get('quest')
            if category == 'stu_id':
                stu_queryset = models.Student.objects.filter(stu_id__contains=quest)
            elif category == 'stu_name':
                stu_queryset = models.Student.objects.filter(stu_name__contains=quest)
            elif category == 'stu_college':
                stu_queryset = models.Student.objects.filter(stu_college__contains=quest)
            elif category == 'stu_major':
                stu_queryset = models.Student.objects.filter(stu_major__contains=quest)
            elif category == 'stu_phone':
                stu_queryset = models.Student.objects.filter(stu_phone__contains=quest)
            if stu_queryset:
                err = ''
            else:
                err = '不存在该学生信息'
        else:
            err = ''
        if form_id == 'delete':
            stu_id = request.POST.get('stu_id')
            img = models.Student.objects.filter(stu_id=stu_id).values('avatar')
            file_name = f"{stu_id}.jpg"
            where = os.path.join(settings.MEDIA_ROOT, 'stuUsers', file_name)
            if img:
                if os.path.exists(where):
                    os.remove(where)
            if models.Student.objects.filter(stu_id=stu_id).exists():
                models.Student.objects.filter(stu_id=stu_id).delete()
    else:
        err = ''
    paginator = Paginator(stu_queryset, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, "adm/adm_stuInfo.html", {'adm_id': adm.adm_id, 'stu_queryset': page_obj,
                                                    'quest': quest, 'category': category, 'err': err})


def adm_book(request):
    book_queryset = models.Book.objects.all()
    paginator = Paginator(book_queryset, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    quest = request.GET.get('quest')
    category = request.GET.get('category')
    if request.method == "GET":
        if category == 'book_name':
            book_queryset = models.Book.objects.filter(book_name__contains=quest)
        elif category == 'book_author':
            book_queryset = models.Book.objects.filter(book_author__contains=quest)
        elif category == 'book_publisher':
            book_queryset = models.Book.objects.filter(book_publisher__contains=quest)
        elif category == 'book_id':
            book_queryset = models.Book.objects.filter(book_id__contains=quest)
    if request.method == "POST":
        category = request.POST.get('category')  # 获取下拉框的值
        form_id = request.POST.get('form_id')
        if form_id == 'search':  # 查询图书
            quest = request.POST.get('quest')
            if category == 'book_name':
                book_queryset = models.Book.objects.filter(book_name__contains=quest)
            elif category == 'book_author':
                book_queryset = models.Book.objects.filter(book_author__contains=quest)
            elif category == 'book_publisher':
                book_queryset = models.Book.objects.filter(book_publisher__contains=quest)
            elif category == 'book_id':
                book_queryset = models.Book.objects.filter(book_id__contains=quest)
            if book_queryset:
                err = ''
            else:
                err = '不存在该图书'
        else:
            err = ''
        if form_id == 'delete':
            book_id = request.POST.get('book_id')
            img = models.Book.objects.filter(book_id=book_id).values('book_img')
            file_name = f"{book_id}.png"
            where = os.path.join(settings.MEDIA_ROOT, 'book', file_name)
            if img:
                if os.path.exists(where):
                    os.remove(where)
            if models.Book.objects.filter(book_id=book_id).exists():
                models.Book.objects.filter(book_id=book_id).delete()
    else:
        err = ''
    paginator = Paginator(book_queryset, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, "adm/adm_book.html", {'adm_id': adm.adm_id, 'book_queryset': page_obj, 'quest': quest,
                                                 'category': category, 'err': err})


def adm_bookInfo(request):
    if request.method == "POST":
        book_id = request.POST.get('book_id')
        book = models.Book.objects.get(book_id=book_id)
        return render(request, "adm/adm_bookInfo.html", {'adm_id': adm.adm_id, 'book': book})
    return render(request, "adm/adm_bookInfo.html", {'adm_id': adm.adm_id})


def adm_bookAlter(request):
    if request.method == "POST":
        form_id = request.POST.get('form_id')
        if form_id == 'info2Alter':
            book_id = request.POST.get('book_id')
            book = models.Book.objects.get(book_id=book_id)
            return render(request, "adm/adm_bookAlter.html", {'book': book})
        book_id = request.POST.get('book_id')
        book_name = request.POST.get('book_name')
        book_author = request.POST.get('book_author')
        book_pubDate = request.POST.get('book_pubDate')
        book_publisher = request.POST.get('book_publisher')
        book_price = request.POST.get('book_price')
        book_num = request.POST.get('book_num')
        book_total = request.POST.get('book_total')
        book_intro = request.POST.get('book_intro')
        bk = models.Book.objects.get(book_id=book_id)
        bk.admId_id = admdd.adm_id
        bk.book_name = book_name
        bk.book_author = book_author
        bk.book_pubDate = book_pubDate
        bk.book_publisher = book_publisher
        bk.book_price = book_price
        bk.book_num = book_num
        bk.book_total = book_total
        bk.book_intro = book_intro
        bk.save()
        # 获取一个文件管理器对象
        file = request.FILES['pic']
        file_name = f"{bk.book_id}.png"
        new_name = f"/media/book/{bk.book_id}.png"
        where = os.path.join(settings.MEDIA_ROOT, 'book', file_name)
        if bk.book_img:
            if os.path.exists(where):
                os.remove(where)
        with open(where, 'wb') as f:
            for chunk in file.chunks():
                f.write(chunk)
        Book.objects.filter(book_id=bk.book_id).update(book_img=new_name)
        notice = models.Notice.objects.all()
        paginator = Paginator(notice, 5)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        return render(request, "adm/adm_index.html", {'admdd': admdd, 'notice': page_obj})
    return render(request, "adm/adm_bookAlter.html", {'admdd': admdd})  # {'stu_id': stu.stu_id}


def adm_bookAdd(request):
    if request.method == "POST":
        book_id = request.POST.get('book_id')
        book_name = request.POST.get('book_name')
        book_author = request.POST.get('book_author')
        book_pubDate = request.POST.get('book_pubDate')
        book_publisher = request.POST.get('book_publisher')
        book_price = request.POST.get('book_price')
        book_num = request.POST.get('book_num')
        book_total = request.POST.get('book_total')
        book_intro = request.POST.get('book_intro')
        models.Book.objects.create(book_id=book_id, admId_id=admdd.adm_id, book_name=book_name, book_author=book_author,
                                   book_pubDate=book_pubDate, book_publisher=book_publisher, book_price=book_price,
                                   book_num=book_num, book_total=book_total, book_intro=book_intro)
        # 获取一个文件管理器对象
        file = request.FILES['pic']
        file_name = f"{book_id}.png"
        new_name = f"/media/book/{book_id}.png"
        where = os.path.join(settings.MEDIA_ROOT, 'book', file_name)
        with open(where, 'wb') as f:
            for chunk in file.chunks():
                f.write(chunk)
        Book.objects.filter(book_id=book_id).update(book_img=new_name)
        notice = models.Notice.objects.all()
        paginator = Paginator(notice, 5)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        return render(request, "adm/adm_index.html", {'admdd': admdd, 'notice': page_obj})
    return render(request, "adm/adm_bookAdd.html")


def adm_borrow(request):
    bw = models.Borrow.objects.all()
    paginator = Paginator(bw, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    quest = request.GET.get('quest')
    category = request.GET.get('category')
    isReturn = request.GET.get('isReturn')
    if request.method == "GET":
        if category == 'book_id':
            if isReturn == 'all':
                bw = models.Borrow.objects.filter(bookId_id=quest)
            elif isReturn == 'yes':
                bw = models.Borrow.objects.filter(bookId_id=quest, isReturn=True)
            elif isReturn == 'no':
                bw = models.Borrow.objects.filter(bookId_id=quest, isReturn=False)
        elif category == 'stu_id':
            if isReturn == 'all':
                bw = models.Borrow.objects.filter(stuId_id=quest)
            elif isReturn == 'yes':
                bw = models.Borrow.objects.filter(stuId_id=quest, isReturn=True)
            elif isReturn == 'no':
                bw = models.Borrow.objects.filter(stuId_id=quest, isReturn=False)
    if request.method == "POST":
        category = request.POST.get('category')  # 获取下拉框的值
        isReturn = request.POST.get('isReturn')
        form_id = request.POST.get('form_id')
        page = request.POST.get('page')
        if form_id == 'search':  # 查询借阅记录
            quest = request.POST.get('quest')
            if category == 'book_id':
                if isReturn == 'all':
                    bw = models.Borrow.objects.filter(bookId_id=quest)
                elif isReturn == 'yes':
                    bw = models.Borrow.objects.filter(bookId_id=quest, isReturn=True)
                elif isReturn == 'no':
                    bw = models.Borrow.objects.filter(bookId_id=quest, isReturn=False)
            elif category == 'stu_id':
                if isReturn == 'all':
                    bw = models.Borrow.objects.filter(stuId_id=quest)
                elif isReturn == 'yes':
                    bw = models.Borrow.objects.filter(stuId_id=quest, isReturn=True)
                elif isReturn == 'no':
                    bw = models.Borrow.objects.filter(stuId_id=quest, isReturn=False)
            if bw:
                err = ''
            else:
                err = '不存在该借阅记录'
        else:
            err = ''
        if form_id == 'delete':
            borrow_id = request.POST.get('borrow_id')
            if models.Borrow.objects.filter(borrow_id=borrow_id).exists():
                models.Borrow.objects.filter(borrow_id=borrow_id).delete()
    else:
        err = ''
    paginator = Paginator(bw, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, "adm/adm_borrow.html", {'adm_id': adm.adm_id, 'bw': page_obj, 'quest': quest,
                                                   'category': category, 'isReturn': isReturn,'err': err})


def createPhoneCode(phone):
    host = 'https://zwp.market.alicloudapi.com'
    path = '/sms/sendv2'
    method = 'GET'
    appcode = '你的appcode'
    coding = str(random.randint(100000, 999999))
    msg = '【智能云】您的验证码是' + coding + '。如非本人操作，请忽略本短信'
    utfmsg = msg.encode('utf-8')
    querys = 'mobile=' + phone + '&content=' + urllib.parse.quote(utfmsg)
    bodys = {}
    url = host + path + '?' + querys
    http = urllib3.PoolManager()
    headers = {
        'Authorization': 'APPCODE ' + appcode
    }
    response = http.request('GET', url, headers=headers)
    content = response.data.decode('utf-8')
    return coding



def export_to_excel(request):
    quest = request.GET.get('quest')
    category = request.GET.get('category')
    isReturn = request.GET.get('isReturn')
    exportId = request.GET.get('exportId')
    if request.method == 'GET':
        # 创建Excel
        wb = Workbook()
        ws = wb.active
        if exportId == 'borrow':
            ws.title = 'BorrowData'  # 设置工作表标题
            # 写入表头
            headers = [field.name for field in models.Borrow._meta.fields]  # 获取模型字段作为表头
            if category == 'book_id':
                if isReturn == 'all':
                    bw = models.Borrow.objects.filter(bookId_id=quest)
                elif isReturn == 'yes':
                    bw = models.Borrow.objects.filter(bookId_id=quest, isReturn=True)
                elif isReturn == 'no':
                    bw = models.Borrow.objects.filter(bookId_id=quest, isReturn=False)
            elif category == 'stu_id':
                if isReturn == 'all':
                    bw = models.Borrow.objects.filter(stuId_id=quest)
                elif isReturn == 'yes':
                    bw = models.Borrow.objects.filter(stuId_id=quest, isReturn=True)
                elif isReturn == 'no':
                    bw = models.Borrow.objects.filter(stuId_id=quest, isReturn=False)
            else:
                bw = models.Borrow.objects.all()
            data = bw
        elif exportId == 'student':
            ws.title = 'StudentData'  # 设置工作表标题
            # 写入表头
            headers = [field.name for field in models.Student._meta.fields]  # 获取模型字段作为表头
            if category == 'stu_id':
                st = models.Student.objects.filter(stu_id__contains=quest)
            elif category == 'stu_name':
                st = models.Student.objects.filter(stu_name__contains=quest)
            elif category == 'stu_college':
                st = models.Student.objects.filter(stu_college__contains=quest)
            elif category == 'stu_major':
                st = models.Student.objects.filter(stu_major__contains=quest)
            elif category == 'stu_phone':
                st = models.Student.objects.filter(stu_phone__contains=quest)
            else:
                st = models.Student.objects.all()
            data = st
        elif exportId == 'book':
            ws.title = 'BookData'  # 设置工作表标题
            # 写入表头
            headers = [field.name for field in models.Book._meta.fields]  # 获取模型字段作为表头
            if category == 'book_id':
                bk = models.Book.objects.filter(book_id__contains=quest)
            elif category == 'book_name':
                bk = models.Book.objects.filter(book_name__contains=quest)
            elif category == 'book_author':
                bk = models.Book.objects.filter(book_author__contains=quest)
            elif category == 'book_publisher':
                bk = models.Book.objects.filter(book_publisher__contains=quest)
            else:
                bk = models.Book.objects.all()
            data = bk
        for col_num, header in enumerate(headers, 1):
            ws.cell(row=1, column=col_num, value=header)
        # 写入数据
        for row_num, obj in enumerate(data, 2):  # 从第二行开始写入数据
            for col_num, header in enumerate(headers, 1):
                cell_value = getattr(obj, header)
                ws.cell(row=row_num, column=col_num, value=str(cell_value))
        response = HttpResponse(
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = 'attachment; filename= "data.xlsx"'
        wb.save(response)
        return response

